package com.cumt.framework.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * Created by caicf on 2017/1/8.
 */
@Component
public class ServiceBeanContext implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(ServiceBeanContext.class);

    private static ApplicationContext context;

    private static ServiceBeanContext instance;

    private ServiceBeanContext() {
    }

    public static ServiceBeanContext getInstance() {
        if (instance == null) {
            synchronized (ServiceBeanContext.class) {
                if (instance == null) {
                    instance = new ServiceBeanContext();
                }
            }
        }
        return instance;
    }


    public ApplicationContext getApplicationContext() {
        return context;
    }

    public Object getBean(String name) {
        Assert.hasText(name);
        return context.getBean(name);
    }

    public <T> T getBean(String name, Class<T> type) {
        Assert.hasText(name);
        Assert.notNull(type);
        return context.getBean(name, type);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        if (context == null) {
            context = new ClassPathXmlApplicationContext("applicationContext.xml");
        }
        log.info("ServiceBeanContext setApplicationContext!");
    }
}
